<?php
include "../service/imageService.php";
include "../service/eventService.php";
include "../util/ftp.php";

function uploadImageEvent($image, $name, $eventId){
	$imagePath = getFTPRealPath()."images/event/".$eventId."/";
	if(!is_dir($imagePath)) ftp_makeDir($imagePath);
	$newName = $name.findExts($image["name"]);
	
	if (!isset($image['name']) || $image['name'] == '') {
        return '';
	} else {
		if ((($image["type"] == "image/gif")
                || ($image["type"] == "image/jpg")
                || ($image["type"] == "image/jpeg")
                || ($image["type"] == "image/pjpeg")
                || ($image["type"] == "image/png"))) {

            move_uploaded_file($image["tmp_name"], "../images/event/".$eventId."/" . $newName);
        } else {
            return '';
        }
	}
	return $newName;
}

$img = $_FILES['img'];
$name = $_POST["nextId"];
$eventId = $_GET["eventId"];

if($eventId == ""){
	if(!isset($_POST["titleVn"]) ||
	   !isset($_POST["titleEn"]) ||
	   !isset($_POST["contentEn"]) ||
	   !isset($_POST["contentVn"])){
		   Header("Location: ../admin/event-detail.php");
	 } else {
		 addEvent(trim($_POST["titleEn"]), trim($_POST["titleVn"]), trim($_POST["contentEn"]), trim($_POST["contentVn"]), $status);
		 $eventId = ConnectionManager::getInstance()->getLastId();
		 if($status == 1) updateEventStatus($eventId, 0);
	 }
} else {
	updateEvent($eventId, trim($_POST["titleEn"]), trim($_POST["titleVn"]), trim($_POST["contentEn"]), trim($_POST["contentVn"]));
	if($status == 1) updateEventStatus($eventId, 0);
}

if(uploadImageEvent($img, $name, $eventId) != ""){
	Header("Location: ../admin/event-detail.php?id=$eventId&msg=5");
} else {
	Header("Location: ../admin/event-detail.php?id=$eventId&msg=6");
}
?>